#!/bin/bash
# 日志函数
log() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $1"
}
# 检查参数是否为空
if [ $# -eq 0 ]; then
    echo "错误：请提供一个地址作为参数。"
    exit 1
fi

# 获取所有参数
args=("$@")
# 用户输入的地址
ops_url="${args[0]}"
# 移除URL中的反斜杠
# shellcheck disable=SC2001
ops_url=$(echo "$ops_url" | sed 's/\\//g')
# 用户输入的默认位置
ops_base_path="${args[1]}"
#ops_url='https://vops.hszq8.com/app/flow/flow_detail?flow_type=story&flow_id=683'  -新的发布单
# 1. 调用接口获取git地址数组
vops_result=$(curl -s https://admin-feature.vbkrhk.com/auto-ai/vops/user/effective/token)


# 使用jq来提取data字段的值
token=$(echo "$vops_result" | jq -r '.data')

echo "token获取成功 token: $token"
# 识别URL类型
if [[ $ops_url == *"flow_type"* && $ops_url == *"flow_id"* ]]; then
    # 解析URL参数
    flow_type=$(echo "$ops_url" | awk -F'[?&]' '{for(i=1;i<=NF;i++){if($i ~ /^flow_type=/){split($i,a,"="); print a[2]}}}')
    flow_id=$(echo "$ops_url" | awk -F'[?&]' '{for(i=1;i<=NF;i++){if($i ~ /^flow_id=/){split($i,a,"="); print a[2]}}}')

    # 检查是否成功提取了flow_type和flow_id
    if [ -z "$flow_type" ] || [ -z "$flow_id" ]; then
        log "错误：无法解析flow_type和flow_id，请检查输入的URL。流程终止。"
        exit 1
    fi

    echo "解析发布单成功 flow_type：$flow_type flow_id：$flow_id"
    # 定义API地址和参数
    # 检查用户输入的默认位置是否存在且不是空字符串
    if [ -n "${args[1]}" ]; then
        # 用户输入的默认位置存在且不为空字符串
        ops_base_path="${args[1]}"
        log "用户输入的默认位置为：$ops_base_path"
        work_item_name_cleaned="$ops_base_path"
    else
        # 用户输入的默认位置不存在或为空字符串
        log "警告：用户未提供默认位置。将使用发布单名称作为地址"
        # 发送API请求并获取响应
        api_detail_response=$(curl -s  "https://vops.hszq8.com/app/api/v1/flow/get_flow_detail?type=$flow_type&id=$flow_id" \
          -H 'Accept: application/json, text/plain, */*' \
          -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
          -H 'Connection: keep-alive' \
          -H "Cookie: vops_token=$token" \
          -H 'Referer: https://vops.hszq8.com/app/flow/flow_detail' \
          -H 'Sec-Fetch-Dest: empty' \
          -H 'Sec-Fetch-Mode: cors' \
          -H 'Sec-Fetch-Site: same-origin' \
          -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0' \
          -H 'sec-ch-ua: "Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"' \
          -H 'sec-ch-ua-mobile: ?0' \
          -H 'sec-ch-ua-platform: "macOS"')
        # 打印请求返回的body内容
        echo "API响应内容：$api_detail_response"
        # 检查status是否为success
        # 检查status是否为success
        status=$(echo "$api_detail_response" | jq -r '.status')
        if [ "$status" != "success" ]; then
          echo "get_flow_detail调用失败，返回状态为 $status 。流程终止。"
          exit 1
        fi
       # 解析data里面的项目信息
        work_item_name=$(echo "$api_detail_response" | jq -r '.data.work_item_name')
        # 替换工作项名称中的斜杠字符为竖线
        work_item_name_cleaned=$(echo "$work_item_name" | sed 's/\//|/g')
        echo "文件夹名字为: $work_item_name"
    fi

    # 指定项目克隆目录
    # shellcheck disable=SC2088
    clone_dir="$HOME/code/java/ops/$work_item_name_cleaned"
    # 检查目录是否存在，如果不存在则创建它
    if [ ! -d "$clone_dir" ]; then
        mkdir -p "$clone_dir"
    fi

    # 定义API地址和参数
    # 发送API请求并获取响应
    api_response=$(curl -s "https://vops.hszq8.com/app/api/v1/flow/get_app_and_branch?type=$flow_type&id=$flow_id" \
      -H 'Accept: application/json, text/plain, */*' \
      -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
      -H 'Connection: keep-alive' \
      -H "Cookie: vops_token=$token" \
      -H 'Referer: https://vops.hszq8.com/app/flow/flow_detail' \
      -H 'Sec-Fetch-Dest: empty' \
      -H 'Sec-Fetch-Mode: cors' \
      -H 'Sec-Fetch-Site: same-origin' \
      -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0' \
      -H 'sec-ch-ua: "Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"' \
      -H 'sec-ch-ua-mobile: ?0' \
      -H 'sec-ch-ua-platform: "macOS"')

    # 检查status是否为success
    status=$(echo "$api_response" | jq -r '.status')
    if [ "$status" != "success" ]; then
      echo "get_app_and_branch 调用失败，返回状态为 $status 。流程终止。"
      exit 1
    fi

    # 解析data里面的项目信息
    projects=$(echo "$api_response" | jq -r '.data | length')
    echo "发布单中总项目个数: $projects"
    # 循环解析项目信息
    # shellcheck disable=SC2004
    for ((i=0; i<$projects; i++)); do
      {
      repo_url=$(echo "$api_response" | jq -r ".data[$i].repo_url")
       # 检查是否是 SSH 地址格式
      if [[ $repo_url == git@* ]]; then
          echo "当前 SSH URL: $remote_url"
          # 提取域名和仓库路径
          domain=$(echo $repo_url | sed -E 's/git@([^:]+):.*/\1/')
          path=$(echo $repo_url | sed -E 's/git@[^:]+:(.*)/\1/')

          # 构建 HTTP 地址
          repo_url="http://$domain/$path"
          echo "转换成 HTTP URL: $repo_url"
      fi
      branch=$(echo "$api_response" | jq -r ".data[$i].name")
      repo_name=$(basename "$repo_url" .git)
      echo "项目名：$repo_name 分支名称: $branch, 仓库URL: $repo_url "
      # 构建项目文件夹路径
      project_dir="$clone_dir/$repo_name"
       # 检查项目文件夹是否存在
      if [ -d "$project_dir" ]; then
        echo "项目文件夹 '$project_dir' 已经存在。"
        # 提示用户确认是否继续操作
        # shellcheck disable=SC2106
        continue
      fi
       # 克隆项目并切换到分支
      git clone "$repo_url" "$project_dir" && cd "$project_dir" && git checkout "$branch"
      # shellcheck disable=SC2181
       if [ $? -ne 0 ]; then
           echo "克隆 $repo_url 失败"
       fi
      } &
    done

    wait
    echo "发布单 $ops_url 下载完成"

    # shellcheck disable=SC2162
    read -p "是否打开IntelliJ IDEA？(y/n): " open_confirm
    if [ "$open_confirm" == "y" ]; then
        open -a "IntelliJ IDEA Ultimate" "$clone_dir"
    fi
 exit 1
fi

if [[ $ops_url == *"release/app"* || $ops_url == *"release/deps"* ]]; then
  param=$(basename "$ops_url")
  echo "解析依赖发布单 成功 param：$param"
      # 定义API地址和参数
      # 检查用户输入的默认位置是否存在且不是空字符串
      if [ -n "${args[1]}" ]; then
          # 用户输入的默认位置存在且不为空字符串
          ops_base_path="${args[1]}"
          log "用户输入的默认位置为：$ops_base_path"
          work_item_name_cleaned="$ops_base_path"
      else
          # 用户输入的默认位置不存在或为空字符串
          log "警告：用户未提供默认位置。将使用发布单名称作为地址"
          # 发送API请求并获取响应
          api_detail_response=$(curl -s "https://vops.hszq8.com/app/api/v1/release/$param/info" \
            -H 'Accept: application/json, text/plain, */*' \
            -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
            -H 'Connection: keep-alive' \
            -H "Cookie: vops_token=$token" \
            -H 'Referer: https://vops.hszq8.com/app/flow/flow_detail' \
            -H 'Sec-Fetch-Dest: empty' \
            -H 'Sec-Fetch-Mode: cors' \
            -H 'Sec-Fetch-Site: same-origin' \
            -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0' \
            -H 'sec-ch-ua: "Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"' \
            -H 'sec-ch-ua-mobile: ?0' \
            -H 'sec-ch-ua-platform: "macOS"')
          # 检查status是否为success
          status=$(echo "$api_detail_response" | jq -r '.status')
          if [ "$status" != "success" ]; then
            echo "info 调用失败，返回状态为 $status 。流程终止。"
            exit 1
          fi
         # 解析data里面的项目信息
          work_item_name=$(echo "$api_detail_response" | jq -r '.data.name')
          # 替换工作项名称中的斜杠字符为竖线
          work_item_name_cleaned=$(echo "$work_item_name" | sed 's/\//|/g')
          echo "文件夹名字为: $work_item_name"
      fi

      # 指定项目克隆目录
      # shellcheck disable=SC2088
      clone_dir="$HOME/code/java/ops/$work_item_name_cleaned"
      # 检查目录是否存在，如果不存在则创建它
      if [ ! -d "$clone_dir" ]; then
          mkdir -p "$clone_dir"
      fi

      # 定义API地址和参数
      # 发送API请求并获取响应
      api_response=$(curl -s "https://vops.hszq8.com/app/api/v1/release/$param/app" \
        -H 'Accept: application/json, text/plain, */*' \
        -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
        -H 'Connection: keep-alive' \
        -H "Cookie: vops_token=$token" \
        -H 'Referer: https://vops.hszq8.com/app/flow/flow_detail' \
        -H 'Sec-Fetch-Dest: empty' \
        -H 'Sec-Fetch-Mode: cors' \
        -H 'Sec-Fetch-Site: same-origin' \
        -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0' \
        -H 'sec-ch-ua: "Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"' \
        -H 'sec-ch-ua-mobile: ?0' \
        -H 'sec-ch-ua-platform: "macOS"')

      # 检查status是否为success
      status=$(echo "$api_response" | jq -r '.status')
      if [ "$status" != "success" ]; then
        echo "app 调用失败，返回状态为 $status 。流程终止。"
        exit 1
      fi

      # 解析data里面的项目信息
      projects=$(echo "$api_response" | jq -r '.data | length')
      echo "依赖发布单中 总项目个数: $projects"
      # 循环解析项目信息
      # shellcheck disable=SC2004
      for ((i=0; i<$projects; i++)); do
        {
        repo_url=$(echo "$api_response" | jq -r ".data[$i].scm")
         # 检查是否是 SSH 地址格式
        if [[ $repo_url == git@* ]]; then
            echo "依赖发布单 当前项目 SSH URL: $remote_url"

            # 提取域名和仓库路径
            domain=$(echo $repo_url | sed -E 's/git@([^:]+):.*/\1/')
            path=$(echo $repo_url | sed -E 's/git@[^:]+:(.*)/\1/')

            # 构建 HTTP 地址
            repo_url="http://$domain/$path"
            echo "依赖发布单 更新 HTTP URL: $new_url"
        else
            echo "No SSH URL found for $dir"
        fi
        branch=$(echo "$api_response" | jq -r ".data[$i].branch")
        repo_name=$(basename "$repo_url" .git)
        echo "依赖发布单 项目名：$repo_name 分支名称: $branch, 仓库URL: $repo_url "
        # 构建项目文件夹路径
        project_dir="$clone_dir/$repo_name"
         # 检查项目文件夹是否存在
        if [ -d "$project_dir" ]; then
          echo "依赖发布单 项目文件夹 '$project_dir' 已经存在。"
          # 提示用户确认是否继续操作
          # shellcheck disable=SC2106
          continue
        fi
         # 克隆项目并切换到分支
        git clone "$repo_url" "$project_dir" && cd "$project_dir" && git checkout "$branch"
         # 检查克隆是否成功
        # shellcheck disable=SC2181
        if [ $? -ne 0 ]; then
            echo "依赖发布单 克隆 $repo_url 失败"
        fi
        } &
      done

      wait
      echo "$ops_url 下载完成"

        # 用户确认是否打开IntelliJ IDEA
        # shellcheck disable=SC2162
        read -p "是否打开IntelliJ IDEA？(y/n): " open_confirm
        if [ "$open_confirm" == "y" ]; then
            open -a "IntelliJ IDEA Ultimate" "$clone_dir"
        fi

   exit 1
fi


# 发布计划 https://vops.hszq8.com/app/flow/plan_detail?id=948
if [[ $ops_url == *"plan_detail"* ]]; then
    # 解析URL参数
    id=$(echo "$ops_url" | awk -F'[?&]' '{for(i=1;i<=NF;i++){if($i ~ /^id=/){split($i,a,"="); print a[2]}}}')
    # 检查是否成功提取了flow_type和flow_id
    if [ -z "$id" ]; then
        log "错误：无法解析id，请检查输入的URL。流程终止。"
        exit 1
    fi

    echo "解析发布计划成功 id：$id"
    # 定义API地址和参数
    # 检查用户输入的默认位置是否存在且不是空字符串
    if [ -n "${args[1]}" ]; then
        # 用户输入的默认位置存在且不为空字符串
        ops_base_path="${args[1]}"
        log "用户输入的默认位置为：$ops_base_path"
        work_item_name_cleaned="$ops_base_path"
    else
        # 用户输入的默认位置不存在或为空字符串
        log "警告：用户未提供默认位置。将使用发布计划名称作为地址"
        # 发送API请求并获取响应
        api_detail_response=$(curl -s  "https://vops.hszq8.com/app/api/v1/flow_plan/detail/$id" \
          -H 'Accept: application/json, text/plain, */*' \
          -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
          -H 'Connection: keep-alive' \
          -H "Cookie: vops_token=$token" \
          -H 'Referer: https://vops.hszq8.com/app/flow/flow_detail' \
          -H 'Sec-Fetch-Dest: empty' \
          -H 'Sec-Fetch-Mode: cors' \
          -H 'Sec-Fetch-Site: same-origin' \
          -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0' \
          -H 'sec-ch-ua: "Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"' \
          -H 'sec-ch-ua-mobile: ?0' \
          -H 'sec-ch-ua-platform: "macOS"')
        # 打印请求返回的body内容
        echo "API响应内容：$api_detail_response"
        # 检查status是否为success
        # 检查status是否为success
        status=$(echo "$api_detail_response" | jq -r '.status')
        if [ "$status" != "success" ]; then
          echo "detail调用失败，返回状态为 $status 。流程终止。"
          exit 1
        fi
        # 解析data里面的项目信息
        work_item_name=$(echo "$api_detail_response" | jq -r '.data.title')
        # 替换工作项名称中的斜杠字符为竖线
        work_item_name_cleaned=$(echo "$work_item_name" | sed 's/\//|/g')
        echo "文件夹名字为: $work_item_name"
    fi

    # 指定项目克隆目录
    # shellcheck disable=SC2088
    clone_dir="$HOME/code/java/ops/$work_item_name_cleaned"
    # 检查目录是否存在，如果不存在则创建它
    if [ ! -d "$clone_dir" ]; then
        mkdir -p "$clone_dir"
    fi

    # 定义API地址和参数
    # 发送API请求并获取响应
    api_response=$(curl -s "https://vops.hszq8.com/app/api/v1/flow_plan/plan_version_branch/$id" \
      -H 'Accept: application/json, text/plain, */*' \
      -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
      -H 'Connection: keep-alive' \
      -H "Cookie: vops_token=$token" \
      -H 'Referer: https://vops.hszq8.com/app/flow/flow_detail' \
      -H 'Sec-Fetch-Dest: empty' \
      -H 'Sec-Fetch-Mode: cors' \
      -H 'Sec-Fetch-Site: same-origin' \
      -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0' \
      -H 'sec-ch-ua: "Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"' \
      -H 'sec-ch-ua-mobile: ?0' \
      -H 'sec-ch-ua-platform: "macOS"')

    # 检查status是否为success
    status=$(echo "$api_response" | jq -r '.status')
    if [ "$status" != "success" ]; then
      echo "plan_version_branch 调用失败，返回状态为 $status 。流程终止。"
      exit 1
    fi

    # 解析data里面的项目信息
    projects=$(echo "$api_response" | jq -r '.data | length')
    echo "发布计划中总项目个数: $projects"
    # 循环解析项目信息
    # shellcheck disable=SC2004
    for ((i=0; i<$projects; i++)); do
      {
      repo_url=$(echo "$api_response" | jq -r ".data[$i].repo_url")
       # 检查是否是 SSH 地址格式
      if [[ $repo_url == git@* ]]; then
          echo "发布计划 当前 SSH URL: $remote_url"
          # 提取域名和仓库路径
          domain=$(echo $repo_url | sed -E 's/git@([^:]+):.*/\1/')
          path=$(echo $repo_url | sed -E 's/git@[^:]+:(.*)/\1/')

          # 构建 HTTP 地址
          repo_url="http://$domain/$path"
          echo "发布计划 转换成 HTTP URL: $new_url"
      else
          echo "No SSH URL found for $dir"
      fi
      branch=$(echo "$api_response" | jq -r ".data[$i].name")
      repo_name=$(basename "$repo_url" .git)
      echo "发布计划 项目名：$repo_name 分支名称: $branch, 仓库URL: $repo_url "
      # 构建项目文件夹路径
      project_dir="$clone_dir/$repo_name"
       # 检查项目文件夹是否存在
      if [ -d "$project_dir" ]; then
        echo "项目文件夹 '$project_dir' 已经存在。"
        # 提示用户确认是否继续操作
        # shellcheck disable=SC2106
        continue
      fi
       # 克隆项目并切换到分支
      git clone "$repo_url" "$project_dir" && cd "$project_dir" && git checkout "$branch"
      # shellcheck disable=SC2181
       if [ $? -ne 0 ]; then
           echo "克隆 $repo_url 失败"
       fi
      } &
    done

    wait
    echo "发布计划 $ops_url 下载完成"

    # shellcheck disable=SC2162
    read -p "是否打开IntelliJ IDEA？(y/n): " open_confirm
    if [ "$open_confirm" == "y" ]; then
        open -a "IntelliJ IDEA Ultimate" "$clone_dir"
    fi
 exit 1

fi


echo "错误：不支持的地址。1"
